// WebRTC服务类 - 管理WebRTC连接
class WebRTCServiceClass {
  // 构造函数
  constructor() {
    // WebRTC连接对象
    this.peerConnection = null
    
    // 会话ID - 从全局配置中获取默认值
    this.sessionId = process.env.SESSION_CONFIG.DEFAULT_SESSION_ID
    
    // 连接状态
    this.connectionStatus = 'disconnected'
    
    // 连接状态变化回调函数
    this.onConnectionStatusChange = null
    
    // WebRTC配置 - 从全局配置获取
    this.sdpSemantics = process.env.WEBRTC_CONFIG.sdpSemantics
    
    // STUN服务器使用状态
    this.useStun = false
    
    // ICE服务器配置
    this.iceServers = []
  }
  

  
  // 设置连接状态变化回调
  setOnConnectionStatusChange(callback) {
    this.onConnectionStatusChange = callback
  }
  
  // 更新连接状态
  updateConnectionStatus(status) {
    this.connectionStatus = status
    if (this.onConnectionStatusChange) {
      this.onConnectionStatusChange(status)
    }
    
    // 触发全局事件，以便其他组件可以监听
    if (typeof window !== 'undefined') {
      if (status === 'connected' && typeof window.onWebRTCConnected === 'function') {
        window.onWebRTCConnected();
      } else if (status === 'disconnected' && typeof window.onWebRTCDisconnected === 'function') {
        window.onWebRTCDisconnected();
      }
    }
  }
  
  // 创建WebRTC连接
  async createConnection() {
    try {
      // 检查浏览器支持
      if (!window.RTCPeerConnection) {
        throw new Error('浏览器不支持WebRTC')
      }

      this.updateConnectionStatus('connecting')
      
      // 创建RTCPeerConnection
      const config = {
        sdpSemantics: this.sdpSemantics
      }
      
      // 如果配置了ICE服务器，添加到配置中
      if (this.iceServers && this.iceServers.length > 0) {
        config.iceServers = this.iceServers
        console.log('使用ICE服务器配置:', config.iceServers)
      }

      this.peerConnection = new RTCPeerConnection(config)

      // 添加轨道事件监听
      this.peerConnection.ontrack = (evt) => {
        if (evt.track.kind == 'video') {
          const videoElement = document.getElementById('video')
          if (videoElement) {
            videoElement.srcObject = evt.streams[0]
          }
        } else {
          const audioElement = document.getElementById('audio')
          if (audioElement) {
            audioElement.srcObject = evt.streams[0]
          }
        }
      }

      // 连接状态变化处理
      this.peerConnection.onconnectionstatechange = () => {
        const state = this.peerConnection.connectionState
        console.log('WebRTC连接状态变化:', state)

        if (state === 'connected') {
          this.updateConnectionStatus('connected')
        } else if (state === 'disconnected' || state === 'failed' || state === 'closed') {
          this.updateConnectionStatus('disconnected')
        }
      }

      // 开始协商
      await this.negotiate()

    } catch (error) {
      console.error('WebRTC连接创建失败:', error)
      this.updateConnectionStatus('failed')
      throw error
    }
  }
  
  // 协商连接
  async negotiate() {
    try {
      // 添加接收轨道
      this.peerConnection.addTransceiver('video', { direction: 'recvonly' })
      this.peerConnection.addTransceiver('audio', { direction: 'recvonly' })
      
      // 创建offer
      const offer = await this.peerConnection.createOffer()
      await this.peerConnection.setLocalDescription(offer)

      // 等待ICE收集完成
      await new Promise((resolve) => {
        if (this.peerConnection.iceGatheringState === 'complete') {
          resolve()
        } else {
          const checkState = () => {
            if (this.peerConnection.iceGatheringState === 'complete') {
              this.peerConnection.removeEventListener('icegatheringstatechange', checkState)
              resolve()
            }
          }
          this.peerConnection.addEventListener('icegatheringstatechange', checkState)
        }
      })

      // 发送offer到服务器
      const offerData = this.peerConnection.localDescription
      // 解析getUrl函数字符串
      const getUrl = new Function(`return ${process.env.API_CONFIG.getUrl}`)()
      const response = await fetch(getUrl('offer'), {
        body: JSON.stringify({
          sdp: offerData.sdp,
          type: offerData.type,
        }),
        headers: {
          'Content-Type': 'application/json'
        },
        method: 'POST'
      })

      // 处理服务器响应
      const answer = await response.json()
      this.sessionId = answer.sessionid
      
      // 设置远程描述
      await this.peerConnection.setRemoteDescription(answer)
      
      // 更新UI状态
      this.updateConnectionStatus('connected')
      
    } catch (error) {
      console.error('WebRTC协商失败:', error)
      this.updateConnectionStatus('failed')
      throw error
    }
  }
  
  // 获取连接状态
  getConnectionStatus() {
    return this.connectionStatus
  }
  
  // 获取会话ID
  getSessionId() {
    return this.sessionId
  }
  
  // 切换使用STUN服务器
  setUseStun(useStun) {
    this.useStun = useStun
    console.log('STUN服务器使用状态设置为:', useStun)
    
    // 重新初始化ICE服务器配置
    this.iceServers = []
    
    // 如果启用了STUN，添加Google的公共STUN服务器
    if (useStun) {
      this.iceServers.push({
        urls: ['stun:stun.miwifi.com:3478']
      })
      console.log('已添加STUN服务器到ICE配置:', this.iceServers)
    }
  }
  
  // 关闭连接
  closeConnection() {
    try {
      if (this.peerConnection) {
        setTimeout(() => {
          this.peerConnection.close()
        }, 500)
      }

      this.updateConnectionStatus('disconnected')
    } catch (error) {
      console.error('关闭连接失败:', error)
    }
  }
}

// 创建单例实例
const WebRTCService = new WebRTCServiceClass()

// 导出单例
// eslint-disable-next-line import/no-default-export
export default WebRTCService